package controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.Tootaja;
import db.Yyrnik;

public abstract class BaseController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    if(request.getSession().getAttribute("user") == null && request.getSession().getAttribute("admin") == null){
		response.sendRedirect("/websocket/login");
		return;
	    }else{
		Yyrnik y = (Yyrnik) request.getSession().getAttribute("user");
		if(y != null){
		    get(request, response, y.getKasutajanimi());
		}else{
		    Tootaja t = (Tootaja) request.getSession().getAttribute("admin");
		    get(request, response, t.getKasutajanimi());
		}
		
	    }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    if(request.getSession().getAttribute("user") == null && request.getSession().getAttribute("admin") == null){
		response.sendRedirect("/websocket/login");
		return;
	    }else{
		Yyrnik y = (Yyrnik) request.getSession().getAttribute("user");
		if(y != null){
		    post(request, response, y.getKasutajanimi());
		}else{
		    Tootaja t = (Tootaja) request.getSession().getAttribute("admin");
		    post(request, response, t.getKasutajanimi());
		}
		
	    }
	}
	
	protected abstract void get(HttpServletRequest request, HttpServletResponse response, String username) throws ServletException, IOException;
	protected abstract void post(HttpServletRequest request, HttpServletResponse response, String username) throws ServletException, IOException;
}
